const fs = require('fs');
var exec = require('child_process').exec;

function change_d_ts()
{
    let buffer = fs.readFileSync('index.d.ts');
    let str = buffer.toString();
    // console.log(str);
    let find_str = 'declare namespace com {';
    // console.log(str.indexOf(find_str));

    let len = find_str.length;
    let total_len = str.length;
    //1.删除declare namespace com {以及上一级的}
    let pos_end = str.indexOf(find_str) + len;
    let pos_start = 0;
    while(pos_end < total_len && pos_start >= 0)
    {
        pos_start = str.indexOf(find_str,pos_end);
        pos_end = pos_start + len;
        let delete_str = str.slice(pos_start - 3, pos_end + 2);

        console.log('delete_str:',delete_str);
        console.log('pos_start:',pos_start);
        console.log('pos_end:',pos_end);
        str = str.replace(delete_str,"");
        //console.log(str);
    }

    str = str.replace('declare namespace com','declare module "com"');
    console.log(str);
    fs.writeFileSync('index.d.ts',str);

    //index.js添加导出语句
    let buffer1 = fs.readFileSync('index.js');
    let str1 = buffer1.toString();

    str1 = str1 + 'module.exports = com;';
    fs.writeFileSync('index.js',str1);
}

exec('tsc', change_d_ts);